package com.lizard.schedule.persistence.db.table;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.lizard.schedule.persistence.db.DbHelper;
import com.lizard.schedule.persistence.db.bean.IdGeneratorBean;

/**
 * id生成器管理表
 */
public class IdGeneratorTbl {

    private static IdGeneratorTbl instance;

    private IdGeneratorTbl(){}

    public static IdGeneratorTbl getInstance(){
        if(instance == null){
            synchronized (IdGeneratorTbl.class){
                if(instance == null){
                    instance = new IdGeneratorTbl();
                }
            }
        }
        return instance;
    }

    /**
     * 表名
     */
    private final String TBL_NAME = "c_tbl";

    /**
     * 表字段：主键
     */
    private final String FIELD_ID = "_id";

    /**
     * 用户名
     */
    private final String FIELD_USERNAME = "f_a";

    /**
     * 表字段：类型
     * 区分改id是用来标识哪种数据
     */
    private final String FIELD_TYPE = "f_b";

    /**
     * 表字段：id生成源，id生成器根据该数据生成id
     */
    private final String FIELD_GENERATE_ID = "f_c";

    /**
     * 创建表
     *
     * @param db
     */
    public void createTbl(SQLiteDatabase db){
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("CREATE TABLE IF NOT EXISTS ").append(TBL_NAME).append("(")
                .append(FIELD_ID).append(" INTEGER PRIMARY KEY AUTOINCREMENT,")
                .append(FIELD_USERNAME).append(" TEXT,")
                .append(FIELD_TYPE).append(" INTEGER,")
                .append(FIELD_GENERATE_ID).append(" INTEGER DEFAULT 1")
                .append(");");
        db.execSQL(sqlBuilder.toString());
    }

    /**
     * 查找
     *
     * @param username 非注册用户传null
     * @param type
     * @return
     */
    public IdGeneratorBean select(String username, int type){
        IdGeneratorBean idGeneratorBean = null;
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("SELECT * FROM ").append(TBL_NAME)
                .append(" WHERE ").append(FIELD_USERNAME).append(" = ? AND ").append(FIELD_TYPE).append(" = ?;");
        Cursor cursor = DbHelper.getInstance().getSqliteDatabase().rawQuery(sqlBuilder.toString(),
                new String[]{username == null ? "" : username, type+""});
        if(cursor.moveToNext()){
            idGeneratorBean = new IdGeneratorBean(
                    cursor.getString(cursor.getColumnIndex(FIELD_USERNAME)),
                    cursor.getInt(cursor.getColumnIndex(FIELD_TYPE)),
                    cursor.getInt(cursor.getColumnIndex(FIELD_GENERATE_ID))
            );
        }
        cursor.close();
        return idGeneratorBean;
    }

    /**
     * 插入
     *
     * @param idGeneratorBean
     */
    public void insert(IdGeneratorBean idGeneratorBean){
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("INSERT INTO ").append(TBL_NAME)
                .append("(").append(FIELD_USERNAME).append(",").append(FIELD_TYPE).append(",").append(FIELD_GENERATE_ID)
                .append(") VALUES(?,?,?);");
        DbHelper.getInstance().getSqliteDatabase().execSQL(sqlBuilder.toString(), new Object[]{
                idGeneratorBean.getUsername(), idGeneratorBean.getType(), idGeneratorBean.getGenerateId()});
    }

    /**
     * 更新id
     *
     * @param idGeneratorBean
     */
    public void updateGenerateId(IdGeneratorBean idGeneratorBean){
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("UPDATE ").append(TBL_NAME).append(" SET ")
                .append(FIELD_GENERATE_ID).append(" = ? WHERE ")
                .append(FIELD_USERNAME).append(" = ? AND ").append(FIELD_TYPE).append(" = ?;");
        DbHelper.getInstance().getSqliteDatabase().execSQL(sqlBuilder.toString(), new Object[]{
                idGeneratorBean.getGenerateId(),idGeneratorBean.getUsername(),idGeneratorBean.getType()});
    }

    /**
     * 删除表
     *
     * @param db
     */
    public void dropTbl(SQLiteDatabase db){
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("DROP TABLE IF EXISTS ").append(TBL_NAME);
        db.execSQL(sqlBuilder.toString());
    }

}
